package com.lx.spring.config.utils;

import com.lx.spring.config.annotation.MyAnnotation;
import com.lx.spring.config.bean.HelloAnno;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class MyReadAnnotationUtils {

    private static final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    private static final SimpleMetadataReaderFactory registry = new SimpleMetadataReaderFactory();
    private static final StandardEnvironment environment = new StandardEnvironment();

    /**
     * 根据包路径,获取Class的资源路径
     * @param packagePath
     * @return
     */
    public static String getResourcePath(String packagePath){
        if(StringUtils.isEmpty(packagePath)){
            return "";
        }

        String resourcPath =
                ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                        + ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(packagePath))
                        + "/" +"**/*.class";

        return resourcPath;
    }


    /**
     * 获取指定路径下的类
     * @param pkgPath
     * @param annoClazz
     * @return
     */
    public static Set<Class> getClazzFromAnnotation(String pkgPath, Class<? extends Annotation> annoClazz){

        Set<Class> classSet  = new HashSet<Class>();
        //获取spring的包路径
        String pathPackage = getResourcePath(pkgPath);

        Resource[] resources = new Resource[0];

        try {
            //加载路径的资源
            resources = resolver.getResources(pathPackage);
        } catch (IOException e) {
            e.printStackTrace();
            return Collections.emptySet();
        }

        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];

            MetadataReader metadataReader= null;
            Class<?> c2 = null;
            try {
                //读取资源
               metadataReader = registry.getMetadataReader(resource);




                String className= ClassUtils.convertResourcePathToClassName(resource.getFilename());
//                if(StringUtils.endsWith(className, ".class")){
//                    className = pkgPath+"."+StringUtils.remove(className, ".class");
//                }
                className = metadataReader.getClassMetadata().getClassName();

               c2 = Class.forName(className);

            } catch (IOException e) {
                e.printStackTrace();
                continue;
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

//            System.out.println(c2 == metadataReader.);

            //读取注解资源配置
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            //判断是否包含注解
            boolean flag = false;

            if(! annotationMetadata.hasAnnotation(annoClazz.getName())){
                continue;
            }

//            Set<Annotation> annotationSet = new HashSet<Annotation>(Arrays.asList(c2.getDeclaredAnnotations()));
//            if(! annotationSet.contains(annoClazz)){
//                for (Annotation declaredAnnotation : c2.getDeclaredAnnotations()) {
//                    if (StringUtils.equals(declaredAnnotation.annotationType().getName(), annoClazz.getName())) {
//                        flag = true;
//                        break;
//                    }
//                }
//             if(!flag){
//                 continue;
////                 && ! annotationMetadata.hasAnnotation(annoClazz.getName())
//
//            }

            // 获取类信息
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            String className = classMetadata.getClassName();

            try {
                // 加载类
                Class<?> clazz = Class.forName(className);
                classSet.add(clazz);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }


        }
        return classSet;

    }

    public static void main(String[] args) {
        Set<Class> classSet = getClazzFromAnnotation("com.lx.spring.config.bean", MyAnnotation.class);
//        Class he = HelloAnno.class;
//        Set<Class> classSet = getClazzFromAnnotation("com.lx.spring.config.bean", );
        System.out.println(classSet);
    }

    @Test
    public void test1(){
        Set<Class> classSet = getClazzFromAnnotation("com.lx.spring.config.bean", MyAnnotation.class);
        System.out.println(classSet);

    }


}
